"""
des: 多线程耗时任务
author: mr52hz
date: 2024-04-29
"""
from PyQt5.QtCore import QObject, pyqtSignal
from PIL import Image
from fpdf import FPDF

import os
import filetype
import poocr
import settings as st


class ImgToPdfDelayTask(QObject):

    # main 改变路径时触发
    path_changed_signal = pyqtSignal(str)
    scan_img_done_signal = pyqtSignal(str)
    # 执行generate
    generate_pdf_signal = pyqtSignal()
    generating_signal = pyqtSignal(str)
    # 预览或者运行结束
    exported_signal = pyqtSignal(str)

    def __init__(self):
        super(ImgToPdfDelayTask, self).__init__()
        self.img_path = ''
        self.img_name_ls = []
        self.bind()

    def bind(self):
        self.path_changed_signal.connect(self.pathChangeEvent)  # type: ignore
        self.generate_pdf_signal.connect(self.generatePdfEvent)     # type: ignore

    def pathChangeEvent(self, path):
        self.img_path = path
        self.img_name_ls = sorted(name for name in os.listdir(self.img_path))
        pdf_page_tip = f'日志打印\n图像路径：{self.img_path}\n路径下图像以名称排序(与PDF页码一致)'

        for idx, name_l in enumerate(self.img_name_ls, start=1):
            pdf_page_tip += f'\n\t{idx} - {name_l}'
        self.scan_img_done_signal.emit(pdf_page_tip)

    def generatePdfEvent(self):
        export_pdf = FPDF()
        is_any_pdf_page = False
        for img_name in self.img_name_ls:
            img_path = os.path.join(self.img_path, img_name)
            w, h = self.calculatePdfImageWH(img_path)
            if w is None or h is None:
                self.generating_signal.emit(f'\n\t<font color="red"> - {img_name} 未成功添加到PDF中<font>')    # type: ignore
                continue
            else:
                export_pdf.add_page()
                export_pdf.image(img_path, 0, 0, w, h)
                is_any_pdf_page = True
                self.generating_signal.emit(f'\n\t<font color="green"> - {img_name} ok<font>')  # type: ignore
        if is_any_pdf_page:
            export_pdf.output(os.path.join(self.img_path, 'generate.pdf'))
            self.exported_signal.emit(f'\n\n生成成功 generate.pdf位于: \n\t{self.img_path}')  # type: ignore
        else:
            self.exported_signal.emit(f'\n\n<font color="red">该路径下未找到图像文件，未生成PDF！！<font>')  # type: ignore

    @staticmethod
    def calculatePdfImageWH(image_path):
        """
        图像填充 w h计算
            1、先以width填充计算h
            2、如果h超过pdf，那么根据h计算w
        pdf w 210 h 290
        :return: w, h
        """
        if os.path.isdir(image_path):
            return None, None

        file_type = filetype.guess(image_path)

        if not file_type:
            return None, None

        if not file_type.extension.lower() in st.SUPPORT_IMG_FORMAT:
            return None, None

        image = Image.open(image_path)

        img_w, img_h = image.width, image.height
        pdf_w, pdf_h = 210, 290

        # 1、填充pdf_w
        pdf_h_tmp = int(pdf_w * img_h / img_w)

        if pdf_h_tmp <= pdf_h:
            return pdf_w, pdf_h_tmp

        # 2、填充pdf_h
        pdf_w_tmp = int(pdf_h / img_h * img_w)

        return pdf_w_tmp, pdf_h


class IdCardDetectTask(QObject):

    img_changed_signal = pyqtSignal(str)
    detect_signal = pyqtSignal()
    detecting_signal = pyqtSignal()
    detected_signal = pyqtSignal(object)

    def __init__(self):
        super().__init__()
        self.img_path = None
        self.bind()

    def bind(self):
        self.img_changed_signal.connect(self.imgChangedEvent)   # type: ignore
        self.detect_signal.connect(self.startDetectEvent)   # type: ignore

    def imgChangedEvent(self, p):
        self.img_path = p

    def startDetectEvent(self):
        result = poocr.ocr.IDCardOCR(
            # 本地图片
            img_path=self.img_path,
            id=st.TENCENT_ID, key=st.TENCENT_KEY)

        self.detected_signal.emit(result)   # type: ignore
